package sdk.pay.utils.dynamic;

import android.content.Context;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import sdk.pay.constant.PayConstant;
import sdk.pay.utils.PayLogUtil;

/**
 * Created by Joe on 2017/08/09 09:34.
 */

public class PayDynamicFileUtil {

    public static void copyFilesFromAssets(Context context, String savePath) {
        try {
            InputStream is = context.getAssets().open(PayConstant.PATCH_FILE_RESERVE_NAME);
            File f = new File(savePath + File.separator + PayConstant.PATCH_FILE_RESERVE_NAME);
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {//
                // buffer
                fos.write(buffer, 0, byteCount);//
            }
            fos.flush();// cache flush
            is.close();
            fos.close();
            reNameFile(savePath + File.separator);
        } catch (Exception e) {
            e.printStackTrace();
            PayLogUtil.logThird("dynamic jar copy error");
        }
    }

    static void reNameFile(String path) {
        try {
            File file = new File(path + PayConstant.PATCH_FILE_RESERVE_NAME);
            if (file.exists()) {
                boolean v = file.renameTo(new File(path + PayConstant.PATCH_FILE_NAME));
                PayLogUtil.logThird("dynamic jar rename value=" + v);
            } else {
                PayLogUtil.logThird("dynamic jar rename file not exists");
            }
        } catch (Exception e) {
            e.printStackTrace();
            PayLogUtil.logThird("dynamic jar rename error");
        }
    }

    static void deleteFile(String path) {
        try {
            File file = new File(path + PayConstant.PATCH_FILE_NAME);
            if (file.exists()) {
                boolean v = file.delete();
                PayLogUtil.logThird("dynamic jar delete value=" + v);
            }
        } catch (Exception e) {
            e.printStackTrace();
            PayLogUtil.logThird("dynamic jar delete error");
        }
    }
}
